<template>
    <div class="prop-form-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <div class="header-left">
                    <h2>{{ isEdit ? '编辑道具' : '新增道具' }}</h2>
                </div>
                <div class="header-right">
                    <el-button @click="handleCancel">
                        <el-icon>
                            <ArrowLeft />
                        </el-icon>
                        返回
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 表单内容 -->
        <div class="form-content">
            <el-card shadow="never" class="form-card">
                <el-form ref="propFormRef" :model="formData" :rules="formRules" label-width="120px" class="prop-form">

                    <!-- 语言选择 -->
                    <el-form-item label="语言:" prop="language">
                        <el-select v-model="formData.language" placeholder="请选择语言" style="width: 200px">
                            <el-option label="中文" value="zh-CN" />
                            <el-option label="英文" value="en" />
                        </el-select>
                    </el-form-item>

                    <!-- 道具名称 -->
                    <el-form-item label="道具名称:" prop="propName">
                        <el-input v-model="formData.propName" placeholder="请输入道具名称" style="width: 300px" />
                    </el-form-item>

                    <!-- 道具介绍 -->
                    <el-form-item label="道具介绍:" prop="propDescription">
                        <el-input v-model="formData.propDescription" type="textarea" :rows="4" placeholder="请输入道具介绍"
                            style="width: 500px" />
                    </el-form-item>
                    
                    <!-- 道具类型 -->
                    <el-form-item label="道具类型:" prop="propType">
                        <el-select v-model="formData.propType" placeholder="请选择道具类型" style="width: 200px">
                            <el-option label="加速卡" :value="1" />
                            <el-option label="双倍卡" :value="2" />
                        </el-select>
                    </el-form-item>

                    <!-- 开始结束时间 -->
                    <el-form-item label="开始结束:" prop="timeRange">
                        <el-date-picker 
                            v-model="formData.timeRange" 
                            type="datetimerange" 
                            range-separator="至"
                            start-placeholder="请选择开始时间"
                            end-placeholder="请选择结束时间"
                            format="YYYY-MM-DD HH:mm:ss" 
                            value-format="YYYY-MM-DD HH:mm:ss" 
                            style="width: 400px" 
                        />
                    </el-form-item>

                    <!-- 是否限量 -->
                    <el-form-item label="是否限量:" prop="isLimited">
                        <el-radio-group v-model="formData.isLimited">
                            <el-radio :value="0">不限量</el-radio>
                            <el-radio :value="1">限量</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <!-- 限量数量 -->
                    <el-form-item v-if="formData.isLimited === 1" label="限量数量:" prop="limitedQuantity">
                        <el-input v-model="formData.limitedQuantity" placeholder="请输入限量数量" style="width: 200px" />
                    </el-form-item>

                    <!-- 道具图片 -->
                    <el-form-item label="道具图片:" prop="propImage">
                        <el-input v-model="formData.propImage" placeholder="请输入道具图片URL" style="width: 400px" />
                    </el-form-item>

                    <!-- 操作按钮 -->
                    <el-form-item>
                        <div class="form-actions">
                            <el-button @click="handleCancel">取消</el-button>
                            <el-button type="primary" @click="handleSubmit">保存</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeft, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { createProp, updateProp, getPropById } from '@/api/member/props'

const route = useRoute()
const router = useRouter()

// 表单引用
const propFormRef = ref<FormInstance>()

// 是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 表单数据
const formData = reactive({
    id: '',
    propType: null,
    startTime: '',
    endTime: '',
    timeRange: [], // 时间范围
    isLimited: 0,
    limitedQuantity: '',
    sortOrder: '',
    propImage: '',
    status: 1,
    language: '',
    propName: '',
    propDescription: ''
})

// 表单验证规则
const formRules = reactive<FormRules>({
    propType: [
        { required: true, message: '请选择道具类型', trigger: 'change' }
    ],
    timeRange: [
        { required: true, message: '请选择开始结束时间', trigger: 'change' }
    ],
    isLimited: [
        { required: true, message: '请选择是否限量', trigger: 'change' }
    ],
    limitedQuantity: [
        {
            validator: (rule, value, callback) => {
                if (formData.isLimited === 1) {
                    // 限量时，必须输入正整数
                    if (!value) {
                        callback(new Error('请输入限量数量'));
                    } else if (!/^\d+$/.test(value) || parseInt(value) <= 0) {
                        callback(new Error('请输入正整数'));
                    } else {
                        callback();
                    }
                } else {
                    // 不限量时，不需要验证
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    sortOrder: [
        { pattern: /^\d+$/, message: '请输入正整数', trigger: 'blur' }
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ],
    language: [
        { required: true, message: '请选择语言', trigger: 'change' }
    ],
    propName: [
        { required: true, message: '请输入道具名称', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在2到10个字符', trigger: 'blur' }
    ],
    propDescription: [
        { required: true, message: '请输入道具介绍', trigger: 'blur' }
    ]
})

// 取消操作
const handleCancel = () => {
    router.go(-1)
}


// 提交表单
const handleSubmit = async () => {
    if (!propFormRef.value) return

    try {
        await propFormRef.value.validate()

        // 构建提交数据
        const submitData = {
            propType: formData.propType,
            startTime: formData.timeRange && formData.timeRange.length > 0 ? formData.timeRange[0] : undefined,
            endTime: formData.timeRange && formData.timeRange.length > 1 ? formData.timeRange[1] : undefined,
            isLimited: formData.isLimited,
            limitedQuantity: formData.isLimited === 1 ? parseInt(formData.limitedQuantity) : -1, // 不限量时传-1
            sortOrder: formData.sortOrder ? parseInt(formData.sortOrder) : undefined,
            propImage: formData.propImage,
            status: formData.status,
            i18nList: [
                {
                    language: formData.language,
                    propName: formData.propName,
                    propDescription: formData.propDescription
                }
            ]
        }

        let res
        if (isEdit.value) {
            // 编辑模式
            res = await updateProp({ ...submitData, id: formData.id })
        } else {
            // 新增模式
            res = await createProp(submitData)
        }

        const responseData = res as any
        if (responseData && responseData.code === 200) {
            ElMessage.success(`${isEdit.value ? '编辑' : '新增'}成功`)
            router.push('/prop-list')
        } else {
            ElMessage.error((responseData && responseData.msg) || `${isEdit.value ? '编辑' : '新增'}失败`)
        }

    } catch (error) {
        if (error !== false) {
            console.error('提交失败:', error)
            ElMessage.error('操作失败，请稍后重试')
        }
    }
}

// 上传图片
const handleUpload = () => {
    ElMessage.info('图片上传功能待开发')
}

// 加载道具数据（编辑模式）
const loadPropData = async () => {
    if (isEdit.value) {
        try {
            const res = await getPropById(route.params.id as string)
            const responseData = res as any

            if (responseData && responseData.code === 200 && responseData.data) {
                const data = responseData.data
                const i18nData = data.i18nList && data.i18nList.length > 0 ? data.i18nList[0] : {}
                
                // 处理时间范围回显
                const timeRange = []
                if (data.startTime && data.endTime) {
                    timeRange.push(data.startTime, data.endTime)
                }
                
                Object.assign(formData, {
                    id: data.id || '',
                    propType: data.propType || null,
                    startTime: data.startTime || '',
                    endTime: data.endTime || '',
                    timeRange: timeRange, // 时间范围
                    isLimited: data.isLimited || 0,
                    limitedQuantity: data.limitedQuantity && data.limitedQuantity !== -1 ? data.limitedQuantity.toString() : '',
                    sortOrder: data.sortOrder ? data.sortOrder.toString() : '',
                    propImage: data.propImage || '',
                    status: data.status || 1,
                    language: i18nData.language || '',
                    propName: i18nData.propName || '',
                    propDescription: i18nData.propDescription || ''
                })
            } else {
                ElMessage.error('获取道具详情失败')
            }
        } catch (error) {
            console.error('加载道具数据失败:', error)
            ElMessage.error('网络错误，请稍后重试')
        }
    }
}

onMounted(() => {
    loadPropData()
})
</script>

<style scoped>
.prop-form-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

/* 页面头部 */
.page-header {
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
}

.header-right {
    display: flex;
    gap: 12px;
}

/* 表单内容 */
.form-content {
    max-width: 100%;
}

.form-card {
    border-radius: 8px;
    background-color: #fff;
}

.prop-form {
    padding: 20px;
}

.form-hint {
    color: #909399;
    font-size: 12px;
    margin-top: 5px;
    margin-left: 8px;
}

.quantity-section {
    display: flex;
    align-items: center;
}


.image-upload-section {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.image-preview {
    position: relative;
    width: 120px;
    height: 120px;
    border-radius: 50%;
    overflow: hidden;
    border: 2px solid #dcdfe6;
}

.image-preview img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.image-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;
}

.image-preview:hover .image-overlay {
    opacity: 1;
}

.form-actions {
    display: flex;
    gap: 12px;
    margin-top: 20px;
}

/* 日期选择器自定义宽度 */
.date-picker-custom {
    width: 375px !important;
}

:deep(.date-picker-custom .el-input__wrapper) {
    width: 375px !important;
}

:deep(.date-picker-custom .el-input) {
    width: 375px !important;
}

:deep(.date-picker-custom .el-range-editor) {
    width: 375px !important;
}

:deep(.date-picker-custom .el-range-input) {
    width: 375px !important;
}

/* 更强制的方式 */
:deep(.el-date-editor--datetimerange) {
    width: 375px !important;
}

:deep(.el-date-editor--datetimerange .el-input__wrapper) {
    width: 375px !important;
}

/* 全局日期选择器宽度控制 */
:deep(.el-form-item .el-date-editor--datetimerange) {
    width: 375px !important;
    max-width: 375px !important;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-card__body) {
    padding: 0;
}

:deep(.el-form-item) {
    margin-bottom: 24px;
}

:deep(.el-form-item__label) {
    font-weight: 500;
    color: #303133;
}

:deep(.el-input__wrapper) {
    border-radius: 4px;
}

:deep(.el-select .el-input__wrapper) {
    border-radius: 4px;
}

:deep(.el-button) {
    border-radius: 4px;
}

:deep(.el-radio-group) {
    display: flex;
    gap: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .prop-form-container {
        padding: 10px;
    }

    .header-content {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }

    .form-content {
        max-width: 100%;
    }

    .prop-form {
        padding: 15px;
    }

    .quantity-section {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }

    .quantity-section .el-input {
        margin-left: 0 !important;
    }
}
</style>
